package com.sunlee.admin.api.module.job.task;

import com.sunlee.admin.api.module.job.dto.CrawlerResourceTaskDTO;
import com.sunlee.admin.api.module.job.template.CrawResourceTemplate;
import com.sunlee.admin.api.module.job.template.TemplateFactory;
import com.sunlee.admin.api.module.job.template.context.CrawResourceContext;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 爬取第三方PPT资源
 *
 * @author sunulee
 */

@Component("crawlerResourceTask")
public class CrawlerResourceTask implements ITask {


    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 防止重复执行
     */
    private static boolean isRun = false;


    @Override
    public void run(String params) {
        logger.info("crawlerResourceTask定时任务正在执行，参数为：{}", params);

        if (isRun) {
            throw new BusinessException("不可重复执行");
        }

        isRun = true;

        try {
            start(validaDTO(params));
        } finally {
            isRun = false;
            logger.info("crawlerResourceTask定时任务执行结束");
        }
    }


    private void start(CrawlerResourceTaskDTO dto) {
        // 通过来源获取对应模板
        CrawResourceTemplate template = TemplateFactory.getCrawResourceTemplateByCode(dto.getSource());

        // 构建上下文
        CrawResourceContext context = new CrawResourceContext();
        context.setDto(dto);

        // 开始执行
        template.process(context);
    }

    private CrawlerResourceTaskDTO validaDTO(String params) {
        CrawlerResourceTaskDTO dto = validaParseParam(params, CrawlerResourceTaskDTO.class);
        if (Objects.isNull(dto.getTargetFolder())) {
            throw new BusinessException(ErrorCodeEnum.PARAM_NOT_COMPLETE);
        }
        return dto;
    }
}
